package com.bhkj.pdjhbgnewproject.core.register;


import com.bhkj.pdjhbgnewproject.app.App;
import com.bhkj.pdjhbgnewproject.common.contanct.Contacts;
import com.bhkj.pdjhbgnewproject.common.utils.NetIpUtils;
import com.blankj.utilcode.util.LogUtils;
import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;

import java.net.InetAddress;
import java.util.concurrent.TimeUnit;

/**
 * 绑定服务端，通过设备唯一识别id，作为极光推送的的alias
 */
public class RegesterServer {
    private Server server;
    private IServerCallback iServerCallback;
    InetAddress address = null;

    public RegesterServer() {
    }
    public void init(final IServerCallback iServerCallback) {
        this.iServerCallback = iServerCallback;

        address = NetIpUtils.getLocalIPAddress();
        if (iServerCallback == null) {
            return;
        }
        server = AndServer.serverBuilder(App.getCtx())
                .inetAddress(address)
                .port(Contacts.BIND_IP_PORT)
                .timeout(10, TimeUnit.SECONDS)
                .listener(new Server.ServerListener() {
                    @Override
                    public void onStarted() {
                        //服务器启动
                        iServerCallback.onServerStart();
                    }

                    @Override
                    public void onStopped() {
                        //服务器停止
                        iServerCallback.onServerStop();
                    }

                    @Override
                    public void onException(Exception e) {
                        //服务器异常
                        iServerCallback.onServerException(e);
                    }
                }).build();
    }

    private static class Holder {
        private static RegesterServer INSTANCE = new RegesterServer();
    }

    public static RegesterServer getInstance() {
        return Holder.INSTANCE;
    }

    public void startServer() {
        if (server == null) {
            return;
        }
        if (server.isRunning()) {
            //服务正在运行
            LogUtils.i("服务正在运行");
        } else {
            server.startup();
        }

    }

    public void stopServer() {
        if (server == null) {
            return;
        }
        if (server.isRunning()) {
            server.shutdown();
        } else {
            LogUtils.i("服务已经停止");
        }
    }

    public String getIpAddress() {
        if (address == null) {
            return null;
        }
        return address.getHostAddress();
    }
}
